<?php define('APP','newsmgs');
  header('Content-Type:text/html;charset=utf-8');//设置字符编码 
  require 'common/checkFormLib.php';  //引入表单验证函数库
  require 'common/user.dao.php';   //引入用户数据表数据访问层
    //判断$_POST是否为非空数组
 if(!empty($_POST)){    
   $fields=array('uname','upass','upass1','uemail','gender','head','power');
   //表单字段若不为空，则将数据过滤后存入save_data指定字段中
   foreach($fields as $v){
	$save_data[$v]=isset($_POST[$v])?test_input($_POST[$v]):'';	  
  }	
  //$error数组保存验证后的错误信息
  $error=array();
  //验证用户名
  $result=checkUsername($save_data['uname']); 
  if($result !== true){
	 $error['uname']=  $result;
  }
  //验证用户名是否重名
  if( findUserByName($save_data['uname'])){
	  $error['uname']=  '用户名已经存在，请重新选择一个用户名'; 
  }
  //验证密码
  $result=checkPassword($save_data['upass']); 
  if($result !== true){
	 $error['upass']=  $result;
  }    
   //验证重复密码
  $result=checkConfirmPassword($save_data['upass'], $save_data['upass1']); 
  if($result !== true){
	 $error['upass1']=  $result;
  }   
  //验证邮箱
  $result=checkEmail($save_data['uemail']);
  if($result !== true){
	 $error['uemail']=  $result;
  } 
  
  //处理头像文件上传
  $upload_flag=false; //上传成功标志，初始化为false 
  if(!empty($_FILES['myhead'])){	  
	 $myhead=$_FILES['myhead'];	 
	 if($myhead['name']==''){
	    //用户没有选择上传文件，则不做任何处理
	 }else{
	 if($myhead['error']>0){		 
	     $error_msg='上传过程发生错误';	 
	     $error['myhead']=$error_msg;		 
	 }else{		 
		  if($myhead['size']<50000){
			  $type=$myhead['type'];
			  $allow_type=array('image/jpeg','image/png','image/gif');
			  if(in_array($type,$allow_type)){
				  $type=substr(strrchr($myhead['name'],'.'),1);
				  $head=date("YmdHis").rand(100, 999).".".$type;		 	 		 
				  move_uploaded_file($myhead['tmp_name'],"headimg/".$head); 
				  $upload_flag=true;	
			  }else{
				  $error['myhead']='图像类型不符合要求，允许的类型为：' .implode(",",$allow_type);  				  
			  }
		  }else{
			  
			$error['myhead']='文件大小应小于50k';  
		 } 		
     }  
  }
  }
 if(empty($error)){   
    //表单数据全部符合要求
	 if($upload_flag){echo '文件上传成功'; $save_data['head']=$head;}
	   $rs=addUser( $save_data['uname'],$save_data['upass'],$save_data['uemail'] ,$save_data['head'],$save_data['gender'],$save_data['power']);
	   /*
	   //第六章修改用户密码为加密存储后
	   $rs=addUser( $save_data['uname'],md5($save_data['upass']),$save_data['uemail'] ,$save_data['head'],$save_data['gender'],$save_data['power']);
	   */
	 if($rs){
	    header("location: ../index.html");	 //注册成功，跳转到首页
	 }else {
	   $error['error']='用户注册失败';	 
	   require 'common/error.php';	 
	 }		
  }else{
	//调用公共文件error.php显示错误提示信息  
	require 'common/error.php'; 
 }
}
  
?>